package com.lin.mybatis.jsql;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.ExpressionVisitorAdapter;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.StatementVisitorAdapter;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectVisitorAdapter;
import org.junit.jupiter.api.Test;

/**
 * @author linjiang
 * @date 2024/6/12
 * @fn
 */
public class TestVisitor {
    @Test
    public void testExpressionVisitorAdapter() throws JSQLParserException {
        EqualsTo equalsTo = new EqualsTo();
        equalsTo.setLeftExpression(new Column("id"));
        equalsTo.setRightExpression(new LongValue(25));
        /*
         使用访问者设计模式
            访问者：ExpressionVisitorAdapter
            被访问者：EqualsTo
                被访问者使用访问者对自己的属性或方法进行修改。
         */
        equalsTo.accept(new ExpressionVisitorAdapter() {
            @Override
            public void visit(EqualsTo value) {
                super.visit(value);
                System.out.println("这是一个有关表达式的访问者设计模式");
            }
        });
        System.out.println(equalsTo);
    }

    @Test
    public void testSelectVisitorAdapter() throws JSQLParserException {
        Statement statement = CCJSqlParserUtil.parse("select * from user where id in (1,2,3) and name = ?");
        if (statement instanceof Select) {
            Select select = (Select) statement;
            PlainSelect selectBody = (PlainSelect) select.getSelectBody();
            /*
                访问者：SelectVisitorAdapter
                被访问者：PlainSelect
             */
            selectBody.accept(new SelectVisitorAdapter() {
                @Override
                public void visit(PlainSelect plainSelect) {
                    System.out.println(plainSelect);
                    System.out.println("这是一个有关查询的访问者设计模式");
                }
            });
        }
    }

    @Test
    public void test() throws JSQLParserException {
        Statement statement = CCJSqlParserUtil.parse("select * from user where id in (1,2,3) and name = ?");

        /**
         * 访问者：StatementVisitorAdapter
         * 被访问者：Statement
         */
        statement.accept(new StatementVisitorAdapter() {
            @Override
            public void visit(Select select) {
                select.getSelectBody().accept(new SelectVisitorAdapter() {
                    @Override
                    public void visit(PlainSelect plainSelect) {
                        super.visit(plainSelect);
                    }
                });

                System.out.println("这是有关数据库操作的访问者设计模式");
            }
        });

    }
}
